//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Drawing;
using System.Collections;
using System.Collections.Specialized;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CommunityServer;
using CommunityServer.Components;
using System.ComponentModel;
using System.IO;
using System.Web.Security;


namespace CommunityServer.Controls {

	/// <summary>
	/// Summary description for Summary.
	/// </summary>
	[ParseChildren(true)]
	[Obsolete("This class will be removed from CS in future versions.")]
	public abstract class SkinnedWebControl : Control, INamingContainer {

	    CSContext csContext = CSContext.Current;
		string skinFilename = null;
		string skinName = null;
		//string returnURL = null; // Never Used
		ITemplate inlineSkin = null;
	    ControlUserMode mode = ControlUserMode.User;

		// *********************************************************************
		//  SkinnedForumWebControl
		//
		/// <summary>
		/// Constructor
		/// </summary>
		// ***********************************************************************/
        public SkinnedWebControl() 
        {

            skinName = csContext.User.Theme;


        }

        
		// *********************************************************************
		//  CreateChildControls
		//
		/// <summary>
		/// This event handler adds the children controls.
		/// </summary>
		// ***********************************************************************/
		protected override void CreateChildControls() {
			Control skin = null;

			if (inlineSkin != null) {

				inlineSkin.InstantiateIn(this);

				InitializeSkin(this);

			} else {
				// Load the skin
				skin = LoadSkin();

				// Initialize the skin
				InitializeSkin(skin);

				Controls.Add(skin);
			}
		}

		// *********************************************************************
		//  LoadControlSkin
		//
		/// <summary>
		/// Loads the names control template from disk.
		/// </summary>
		// ***********************************************************************/
		protected Control LoadSkin() {
			Control skin;
			string skinPath = Globals.GetSkinPath() + "/Skins/" + SkinFilename.TrimStart('/');
			string defaultSkinPath = Globals.ApplicationPath + "/Themes/default/Skins/" + SkinFilename.TrimStart('/');

			// Do we have a skin?
			if (SkinFilename == null)
				throw new Exception("You must specify a skin.");

			// Attempt to load the control. If this fails, we're done
			try {
				skin = Page.LoadControl(skinPath);
			}
			catch (FileNotFoundException) {

				// Ok we couldn't find the skin, let's attempt to load the default skin instead
				try {

					skin = Page.LoadControl(defaultSkinPath);
				} 
				catch (FileNotFoundException) {
					throw new Exception("Critical error: The skinfile " + skinPath + " could not be found. The skin must exist for this control to render.");
				}
			}

			return skin;
		}

		// *********************************************************************
		//  InitializeSkin
		//
		/// <summary>
		/// Initialize the control template and populate the control with values
		/// </summary>
		// ***********************************************************************/
		protected abstract void InitializeSkin(Control skin);


		// *********************************************************************
		//  SkinName
		//
		/// <summary>
		/// Allows the default control template to be overridden
		/// </summary>
		// ***********************************************************************/
		public string SkinFilename {
			get { 
				return skinFilename; 
			}
			set { 
				skinFilename = value; 
			}
		}

		// *********************************************************************
		//  SkinName
		//
		/// <summary>
		/// Used to construct paths to images, etc. within controls.
		/// </summary>
		/// 
		// ********************************************************************/ 
		protected string SkinName {
			get {
				return skinName;
			}
			set {
				skinName = value;
			}
		}

		public ITemplate Skin {
			get { return inlineSkin; }
			set { inlineSkin = value; }
		}

		public ControlUserMode Mode {
			get { return mode; }
			set { mode = value; }
		}

        protected override void Render(HtmlTextWriter writer)
        {
            SourceMarker(true,writer);
            base.Render (writer);
            SourceMarker(false,writer);
        }

        [System.Diagnostics.Conditional("DEBUG")]
        protected void SourceMarker(bool isStart, HtmlTextWriter writer)
        {
           
            if(isStart)
            {
                writer.WriteLine("<!-- Start: {0} -->", this.GetType());
                
                string skinPath = Globals.GetSkinPath() + "/Skins/" + SkinFilename.TrimStart('/');
                if(System.IO.File.Exists(skinPath))
                    writer.WriteLine("<!-- Skin Path: {0} -->", skinPath);
               else
                   writer.WriteLine("<!-- Skin Path: {0} -->", Globals.ApplicationPath + "/Themes/default/Skins/" + SkinFilename.TrimStart('/'));
            }
            else
                writer.WriteLine("<!-- End: {0} -->", this.GetType());
        }
    

        /// <summary>
        /// Identifies the control that fired posback.
        /// </summary>
        public Control GetPostBackControl (Control container)
        {
            // Note: this is an adapted eggheadcafe.com code.
            //
            Control control = null;

            string ctrlname = Page.Request.Params["__EVENTTARGET"];
            if (ctrlname != null && ctrlname != String.Empty)
            {
                string[] tokens = ctrlname.Split( new char[1] { ':' } );
                if (tokens != null && tokens.GetLength( 0 ) > 0)
                    ctrlname = tokens[(tokens.GetLength( 0 ) - 1)];

                control = container.FindControl( ctrlname );
            }
            else
            {
                // If __EVENTTARGET is null, control is a button type and need to 
                // iterate over the form collection to find it
                //
                string ctrlStr = String.Empty;
                Control c = null;
                foreach (string ctl in Page.Request.Form)
                {

                    // Handle ImageButton controls
                    if (ctl.EndsWith( ".x" ) || ctl.EndsWith( ".y" ))
                    {
                        ctrlStr = ctl.Substring( 0, (ctl.Length - 2) );
                        c = container.FindControl( ctrlStr );
                    }
                    else
                    {
                        c = container.FindControl( ctl );
                    }
                    if (c is System.Web.UI.WebControls.Button ||
                        c is System.Web.UI.WebControls.ImageButton)
                    {
                        control = c;
                        break;
                    }
                }
            }

            return control;
        }

	}
}
